package com.wyu.notaryserver.util;

import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.io.InputStream;
import java.util.UUID;

@Component
public class AliOSSUtil {

    //todo: 存储在个人私用的OSS上，需要改为公有的OSS

    private String endpoint = "oss-cn-guangzhou.aliyuncs.com";
    private String accessKeyId = "LTAI5tS6zTHd83RoKFwcjtfn";
    private String accessKeySecret = "CbG2FWNpHGzuCn03w1jsb5C22isD0l";
    private String bucketName = "web-study02";

    /**
     * 实现图片上传到阿里云
     */
    public String upload(MultipartFile file) throws IOException {
        //获取文件上传的输入流
        InputStream inputStream = file.getInputStream();

        //避免文件覆盖
        String originalFilename = file.getOriginalFilename();
        String fileName = UUID.randomUUID().toString()+originalFilename.substring(originalFilename.lastIndexOf("."));

        //上传文件到阿里云
        OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);
        ossClient.putObject(bucketName, fileName, inputStream);

        //文件url
        String url = "https://" + bucketName + "." + endpoint + "/" + fileName;
        ossClient.shutdown();
        return url;
    }
}
